<!-- 质量报告审核 -->
<template>
  <div>
    <TopFilter ref="TopFilters" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="110" @filterChange="changeHandle" @resetChange="resetHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :dataSource="dataList"
      :datakey="'records'"
      :fetchapi="fetchApi"
      :onColumnsChange="onColumnsChange"
      :onRowSelectChange="selectChange"
    >
      <template slot="controls">
        <multiuse-button :isShow="isDLR" size="small" type="primary" :click="handleAdd">新增</multiuse-button>
        <multiuse-button size="small" type="primary" :click="exportFileBtn.bind()" plain>导出</multiuse-button>
      </template>
    </FilterTable>

    <!-- 弹窗详情表单 -->
    <Drawer :visible.sync="editVisible" :title="setEditFormTitle" destroyOnClose width="80%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <EditForm ref="editFormDom" @close="editClose" @save="editSave" @handleAudit="handleAudit" :rowData="editData" :userInfo="userInfo"></EditForm>
    </Drawer>

    <!--  车辆选择 -->
    <BaseDialog :visible.sync="isShowDialog.car" title="车辆选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <VehicleChoice @close="closeDialog('car')" @onConfirm="handleVehicleChoice" :vinOne="searchVin" />
    </BaseDialog>

    <!--  零件选择 -->
    <BaseDialog :visible.sync="isShowDialog.part" title="零件选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <PartChoice @close="closeDialog('part')" @onConfirm="handlePartChoice" />
    </BaseDialog>

    <!--  服务中心选择 -->
    <BaseDialog :visible.sync="selectDelearFlag" title="服务中心选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DealerList @close="Delearclose" @save="Delearsave" selectionType="multiple" />
    </BaseDialog>

    <img id="barcode" style="display: none" />
  </div>
</template>
<script>
import EditForm from '../common/components/EditForm.vue';
import VehicleChoice from '../common/components/VehicleChoice';
import PartChoice from '../common/components/PartChoice';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import moment from 'moment';
import QRcode from 'qrcode';
import { exportExcelFile } from '@/utils/index';
import { getPartType } from '@/api/dictionary/index.js';
import JsBarcode from 'jsbarcode';
import { dictionary } from '@/utils/dictMixin';
import { getAppId } from '@/assets/js/auth';
// 接口
import { reqListAudit, reqExcelAudit, reqListDLR, reqSaveAudit, getUserInfo } from '@/api/serviceass/qualityManage/audit';

// mock 方法
import mockFun from '@/mock/fun';
const { mockList } = mockFun.qualityManage.mockFunWrap(); // 涉及闭包 所以需要先调用外层函数一次 然后通过解构获取对应mock方法

// 数据格式化
import { formatDataCarInfo, formatDataPartInfo } from '../format';
import { getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index'; //事业部，办事处
import { mapGetters, mapMutations } from 'vuex';
export default {
  name: 'qualityManage',
  mixins: [dictionary],
  components: {
    EditForm,
    VehicleChoice,
    PartChoice,
    DealerList,
  },
  props: {
    // 筛选条件 需要隐藏的字段名
    hideFilterStrArr: {
      type: Array,
      default: () => [''], // ['str1' , 'str2']
    },
  },
  data() {
    return {
      // 筛选条件数据源
      topFilterInit: this.topFilterInitFun(),
      // 列表数据源
      columns: this.creatHeader(),
      // 非单个禁用
      // single: true,
      single: false,
      // 非多个禁用
      multiple: true,
      dataList: [],
      editVisible: false,
      collapse: true,
      // fetchApi: mockList,//mock接口,
      fetchApi: reqListAudit,
      fetchParams: {
        xhrAbort: false,
      }, //ipa 接口
      selectedRows: [], //选中经销商
      disableds: true,
      editData: {}, // 当前编辑数据
      /**
       * 字段映射
       */
      statusMap: {
        DLR: {
          50031001: 'edit',
          50031004: 'edit',
        },
        OEM: {
          50031001: 'audit',
        },
      },
      btnValueMap: {
        edit: '编辑',
        audit: '审核',
      },
      dealerList: [],
      selectDelearFlag: false,
      dealerCompanyCode: [],
      dealerData: [],
      selectDealerData: [],
      userInfoData: [],
      userInfo: '',
    };
  },
  created() {
    /**
     * 默认为最近一周数据
     */
    // this.fetchParams.applyBeginDate = moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');
    // this.fetchParams.applyEndDate = moment().endOf('week').format('YYYY-MM-DD HH:mm:ss');
    getUserInfo().then((res) => {
      if (res.resultCode == 200) {
        this.userInfoData = res.data;
      } else {
        console.log('获取用户信息失败');
      }
    });
  },
  async mounted() {
    if (this.userInfo === '') {
      let companyInfo = await getDealerInfo();
      let params = {};
      if (companyInfo.resultCode === 200) {
        let { dealerCode, dealerName } = companyInfo.data;
        this.userDealerCode = dealerCode;
        params['dealerCode'] = dealerCode;
        params['dealerName'] = dealerName;
      }
      this.userInfo = params;
      this.fetchParams = Object.assign({}, this.fetchParams, { dealerCode: this.userDealerCode }, { xhrAbort: false });
    }
  },
  computed: {
    ...mapGetters('qualityManage', ['pageType', 'editFormStatus', 'isShowDialog', 'searchVin', 'searchDealerName', 'searchDealerCode']),
    isDLR() {
      return this.pageType === 'DLR';
    },
    /**
     * 弹窗标题
     */
    setEditFormTitle() {
      const { editFormStatus } = this;
      const valMap = {
        readonly: '',
        add: '新增',
        ...this.btnValueMap,
      };
      return `${valMap[editFormStatus]}质量报告`;
    },
  },
  methods: {
    ...mapMutations('qualityManage', ['SET_STATE_BY_NAME']),
    /**
     * 获取经销商数据
     */
    async getDealerList() {
      try {
        const { dealerList } = this;
        const res = await reqListDLR();
        console.log(1, res);
        const { data } = res;
        if (data && data.length > 0) {
          data.forEach((item) => {
            dealerList.push({
              name: item.dealerName,
              value: item.dealerCode,
            });
          });
        }
      } catch (err) {
        console.warn('getDealerList=>', err);
      }
    },
    /**
     * 筛选条件配置
     */
    topFilterInitFun() {
      const { setStateParam } = this;
      let data = [
        { type: 'INPUT', label: '质量报告单号', fieldName: 'reportNo', placeholder: '请输入质量报告单号', initialValue: '' },
        { type: 'INPUT', label: 'VIN', fieldName: 'vin', placeholder: '请输入VIN', initialValue: '' },
        {
          type: 'RANGE_DATE',
          label: '报告时间',
          fieldName: 'applyBeginDate|applyEndDate',
          placeholder: '请选择日期',
          initialValue: '',
          rules: [{ required: false, message: '请选择日期', trigger: 'change' }],
        },
        {
          type: 'SELECT',
          label: '服务中心',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => (this.selectDelearFlag = true)} />
              </div>
            );
          },
          onChange: (val) => {
            console.log(val);
          },
          // onInput: val => {
          //   // 修改store中 经销商名
          //   setStateParam('searchDealerName', val)
          //   // 重置store中 经销商code
          //   setStateParam('searchDealerCode', null)
          // }
        },
        {
          type: 'SELECT',
          label: '单据状态',
          fieldName: 'reportStatus',
          placeholder: '请选择',
          initialValue: '',
          itemList: this.createDictListRemoveCodes('5003', ['50031004', '50031005']),
        },

        {
          hidden: true, // 不需要显示的筛选条件，显示的是dealerName， 但接口请参要 dealerCode
          type: 'INPUT',
          label: '服务中心代码',
          fieldName: 'dealerCode',
        },
        { type: 'INPUT', label: '报告主题', fieldName: 'caseMain', placeholder: '请输入报告主题', initialValue: '' },
      ];

      // 过滤需要隐藏的筛选条件
      data = data.filter((item) => !this.hideFilterStrArr.includes(item.fieldName));
      return data;
    },
    /**
     * 显示服务中心选择弹窗
     */
    showDelearDialog() {
      this.showDialog('dealer');
    },
    /**
     * table表头和数据源
     */
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          align: 'center',
          render: (props) => {
            const { getBtnValue, chooseOrderNo } = this;
            const btnVal = getBtnValue(props.row);
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => chooseOrderNo(props.row, 'readonly')}>
                  明细
                </multiuse-button>
                <multiuse-button isShow={Boolean(btnVal)} size="mini" type="text" onClick={() => chooseOrderNo(props.row)}>
                  {btnVal}
                </multiuse-button>
              </div>
            );
          },
        },
        { title: '质量报告单号', dataIndex: 'reportNo', sorter: false },
        { title: '质量报告主题', dataIndex: 'caseMain', sorter: false },
        {
          title: '单据状态',
          dataIndex: 'reportStatus',
          sorter: false,
          filterItems: this.createDictList('5003'),
          dictItems: this.createDictList('5003'),
          render: (props) => {
            return <span>{this.createDictText(props.row.reportStatus, '5003')}</span>;
          },
        },
        { title: '大区', dataIndex: 'bigArea', sorter: false },
        { title: '小区', dataIndex: 'littleArea', sorter: false },
        { title: '服务中心代码', dataIndex: 'dealerCode', sorter: false },
        { title: '服务中心简称', dataIndex: 'dealerName', sorter: false },
        { title: 'VIN', dataIndex: 'vin', sorter: false, width: 150 },
        { title: '车牌号', dataIndex: 'licensePlate', sorter: false },
        { title: '制造基地', dataIndex: 'productingArea', sorter: false },
        { title: '车系', dataIndex: 'seriesName', sorter: false },
        { title: '车型', dataIndex: 'modelName', sorter: false },
        { title: '进站日期', dataIndex: 'stopDate', sorter: true, width: 140 },
        { title: '行驶里程', dataIndex: 'driveMile', sorter: false },
        { title: '报告日期', dataIndex: 'createdAt', sorter: true, width: 140 },
      ];
    },
    /**
     * 通过 reportStatus 获取 详情表单状态标识（readonly、add、edit、audit）
     */
    getFromStatus(reportStatus) {
      const { pageType, statusMap } = this;
      // code(50031001) => status(edit)
      return statusMap[pageType][String(reportStatus)];
    },
    /**
     * 1.判断第二个按钮是否显示
     * 2.以及第二个操作按钮文案：（审核 || 编辑）
     */
    getBtnValue(item) {
      const { btnValueMap, pageType, getFromStatus } = this;
      const { reportStatus } = item;

      // code(50031001) => status(edit) => 按钮字(编辑)
      const btnValue = btnValueMap[getFromStatus(reportStatus)];

      // 经销商 DLR：已提报、已保存   才显示第二个按钮 【编辑】
      // 车  厂 OEM：已提报         才显示第二个按钮 【审核】
      let isShow = false;
      let status = [];
      status = pageType === 'OEM' ? ['50031001'] : ['50031001', '50031004'];
      isShow = status.includes(String(reportStatus));
      return isShow ? btnValue : null;
    },
    /**
     * 设置详情表单状态
     */
    setFromStatus(item, status) {
      const { getFromStatus } = this;
      const { reportStatus } = item;

      const value = status || getFromStatus(reportStatus);
      // 状态有值才设置
      value && this.setStateParam('editFormStatus', value);
    },
    /**
     * 关闭弹窗
     */
    closeDialog(name) {
      this.isShowDialog[name] = false;
      // this.setStateParam('isShowDialog',false)
    },
    /**
     * 显示弹窗
     */
    showDialog(name) {
      this.isShowDialog[name] = true;
      // this.setStateParam('isShowDialog',true)
    },
    /**
     * 修改 store 中的参数 name 为 value
     */
    setStateParam(name, value) {
      const params = { name, value };
      this.SET_STATE_BY_NAME(params);
    },
    /**
     * 新增
     */
    handleAdd() {
      this.setStateParam('editFormStatus', 'add');
      this.editVisible = true;
    },
    /**
     * 车辆选择事件
     */
    handleVehicleChoice(list) {
      console.log('选中的车辆信息=>', list);
      const { setStateParam } = this;
      const value = formatDataCarInfo(list[0]); // 取第一个即可（单选）
      // 修改store中的 curEditFormData
      setStateParam('curEditFormData', value);
      // 调用更新逻辑
      this.$nextTick(() => {
        this.$refs.editFormDom.updateForm();
      });
      this.closeDialog('car');
    },
    /**
     * 零件选择事件
     */
    handlePartChoice(list) {
      console.log('选中的零件信息=>', list);
      const { setStateParam } = this;
      const value = formatDataPartInfo(list[0]); // 取第一个即可（单选）
      // 修改store中的 curEditFormData
      setStateParam('curEditFormData', value);
      // 调用更新逻辑
      this.$nextTick(() => {
        this.$refs.editFormDom.updateForm();
      });
      this.closeDialog('part');
    },
    /**
     * 经销商选择事件
     */
    handleDealerChoice(list) {
      console.log('选中的经销商信息=>', list);

      if (list.length > 0) {
        const dealerName = list[0].dealerName;
        const dealerCode = list[0].dealerCode;

        // 修改筛选条件中对应值
        const arr = this.$refs.TopFilters.list;
        arr.forEach((item) => {
          item.fieldName == 'dealerName' && (item.initialValue = dealerName);
          item.fieldName == 'dealerCode' && (item.initialValue = dealerCode);
        });

        // 修改store中的值
        this.setStateParam('searchDealerName', dealerName);
        this.setStateParam('searchDealerCode', dealerCode);
      }

      this.closeDialog('dealer');
    },
    onColumnsChange(columns) {
      this.columns = columns;
      this.single = columns.length != 1;
      this.multiple = !columns.length;
    },
    // 导出
    async exportFileBtn() {
      try {
        let params = { ...this.fetchParams };
        let res = await reqExcelAudit(params);
        exportExcelFile(res.data, '质量报告审核');
      } catch (err) {
        console.warn(err);
      }
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      this.disableds = this.selectedRows.length <= 0;
      console.log(this.selectedRows);
    },
    chooseOrderNo(val, status) {
      console.log(val);
      val.reporter = this.getUserName(val.reporter);
      // 当前编辑数据
      this.editData = val;
      // 设置表单状态
      this.setFromStatus(val, status);
      this.editVisible = true;
    },
    editClose() {
      this.editVisible = false;
    },
    // 审核操作
    async handleAudit(params) {
      this.editVisible = false;
      console.log('审核操作=>', params);
      const res = await reqSaveAudit(params);
      console.log(1, res);
      if (res.resultCode === 200 && res.success) {
        this.closeDialog();
        this.$refs.table.DO_REFRESH();
      }
    },
    editSave() {
      this.editVisible = false;
      this.fetchParams = { ...this.fetchParams };
    },

    Delearclose() {
      this.selectDelearFlag = false;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign(
        {},
        this.fetchParams,
        val,
        { dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ? this.selectDealerData : null },
        { xhrAbort: false }
      );
      console.log('changeHandle=>', val);
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCompanyCode: null }, { xhrAbort: false });
    },
    //服务中心选择保存
    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach((item) => {
        this.selectDealerData.push(item.dealerCompanyCode);
      });
      this.selectDelearFlag = false;
    },
    getUserName(id) {
      // let data = this.userInfoData.find(item => item.userId == id);
      // if (data) {
      //   return data.userName;
      // } else {
      //   return null;
      // }
      return id;
    },
  },
};
</script>

<style lang="less" scoped></style>
